var providers_json = "";


var makeJSONstring = function(json){
	var myJSON = {};
	myJSON['results'] = [];
	$.map(json.DATA, function(n){
		myJSON['results'].push({
			"id":n[2], "name":n[0] + ", " + n[1]
		});				 
	});
	return myJSON; 
};


var validateElements = function(obj){
	//sets error count to zero, if greater then zero, some data is not valid
	var error_count = 0;
	
	//variables for error messages.
	var require_message = " <span id='error_message'>Field is required.</span>";
	
	//these fields are require on form.
	var required_fields = [
		'meal_date'
	];
	
	//removes error messages from previous validation.
	$(".textbox_error").removeClass();
	$("span[id='error_message']").remove();
	$("#error").hide();
	
	//if fields in the required_fields variable are empty this error is triggered.
	$.map(required_fields,function(field){
		if( !$("#" + field).val() )	{
			error_count++;
			$("#error").show();
			$("#" + field).after(require_message);
			$("#" + field).addClass('textbox_error');
		}
	});	
	
	//if elders drop down and elders_typeing textbox both have data (that can't be valid) this error is triggered.
	if( $("#elders").val() && $("#elders_typein").val() )	{
		error_count++;
		$("#error").show();
		$("#elders, #elders_typein").after(" <span id='error_message'>Choose only one field.</span>");
		$("#elders, #elders_typein").addClass('textbox_error');
	}
	
	//if elders drop down and elders_typeing textbox are both empty this error is triggered
	if( !$("#elders").val() && !$("#elders_typein").val() )	{
		error_count++;
		$("#error").show();
		$("#elders").after(require_message);
		$("#elders").addClass('textbox_error');
	}
	
	//if providers drop down is empty, and elders is empty error is triggered
	if( !$("#providerID").val() && !$("#elders").val() && !$("#elders_typein").val() )	{
		error_count++;
		$("#error").show();
		$("#elders, #providerID").after(require_message);
		$("#elders, #providerID").addClass('textbox_error');
	}
	
	//if providers drop down is empty, and elders is not empty error is triggered
	if( !$("#providerID").val() && $("#elders").val() && !$("#elders_typein").val() )	{
		error_count++;
		$("#error").show();
		$("#providerID").after(require_message);
		$("#providerID").addClass('textbox_error');
	}
	
	//if no errors in validation, well... the data is valid!
	if(error_count){return false;}else{return true;}
};



function clearElements(){
	//resets all elements on page.
	$(":input:not(input[type='button']):not(input[type='select']):not(input[type='hidden'])").val("");
	$("#elders").each( function(){
		// set its value to its first option
		$(this).val( $("#" + $(this).attr("id") + " option:first").val() );
	});
	
	//set today's date
	$("#meal_date").val($("#sign_date").val());
}


function deleteDbObjects(obj_id, api_url){
	var mydata = { id: obj_id };
	$.ajax({
		type:'POST', url:'api.cfm?api=' + api_url, dataType: 'json', async: true, data: mydata,
		success: function() {return true;},
		complete: function(){
			window.location.reload();
			return false;
		},
		error: function(){return false;}
	});	
	
	return false;
}


function bindElements(){
	
	//make meal_date textbox a datepicker
	$("#meal_date").datepicker({ 
		dateFormat: 'mm/dd/yy', changeYear: true, changeMonth: true, yearRange: '1900:2010', autoSize: true,
		prevText: 'Earlier', nextText: 'Later', showOn: 'button', 
		buttonImage: '/CFIDE/scripts/ajax/resources/cf/images/DateChooser.png', buttonImageOnly: true,
		onClose: function(dateText, inst) { $(this).focus() }
	});
	
	//this binds 'add' button's click event to trigger form validation before sending to database.  
	$("#add").bind("click", function(){
		var current_time = new Date();
		//****************************
		if ( validateElements() ){
			var elder_check = "";
			var api_url = "";
			var mydata = {
				providerId: $("#providerID").val(),
				elderId: ( ($("#elders_typein").val()) ? $("#elders_typein").val() : $("#elders").val() ),
				isGuest: ( ($("#elders_typein").val()) ? true : false ),
				mealDate: $("#meal_date").val() + " " + current_time.getHours() + ":" + current_time.getMinutes()
			};
			( ($("#elders_typein").val()) ? 
				api_url = "api.cfm?api=add_guest_to_mealslist" : 
				api_url = "api.cfm?api=add_elder_to_mealslist");
			
			$.ajax({
				type:'POST', url: api_url, dataType: 'json', async: true, data: mydata,
				success: function() { return true;},
				complete: function(){
					clearElements();
					window.location.reload();
				},
				error: function(){return false;}
			})			
		}
		//****************************
	});
	
	//this binds dynamicly added "minus buttons" to a funtion to delete selected list entry
	$("img[id^='elder_']").bind("click", function(){  deleteDbObjects(this.id.split("_")[1], 'delete_elder_from_meallist') });
	
	//this binds dynamicly added "minus buttons" to a funtion to delete selected list entry
	$("img[id^='guest_']").bind("click", function(){  deleteDbObjects(this.id.split("_")[1], 'delete_guest_from_meallist') });
	
}


$(function(){
	clearElements();
	bindElements();
});